﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.ComponentModel;
using System.Text;


namespace Hutchinson.WebControls
{

    /// <summary>
    /// Description résumée de HutchRadioButtonList
    /// </summary>
    [DefaultProperty("Required")]
    public class HutchRadioButtonList : RadioButtonList
    {

        private bool bRequired;


        public HutchRadioButtonList()
        {
            bRequired = false;
        }

        [Bindable(true)]
        [DefaultValue(false)]
        public bool Required
        {
            get
            {
                return bRequired;
            }

            set
            {
                bRequired = value;
            }
        }

        protected override void OnInit(EventArgs e)
        {

            if (!bRequired)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("<script type=\"text/javascript\" language=\"javascript\">");
                sb.AppendLine("function uncheckChecked(obj, listeId)");
                sb.AppendLine("{");
                sb.AppendLine("var Container = document.getElementById(listeId);");
                sb.AppendLine("if (Container.PrevSelectedID == obj.id)");
                sb.AppendLine("{");
                sb.AppendLine("obj.checked = false;");
                sb.AppendLine("Container.PrevSelectedID = \"\";");
                sb.AppendLine("}");
                sb.AppendLine("else");
                sb.AppendLine("Container.PrevSelectedID = obj.id;");
                sb.AppendLine("}");
                sb.AppendLine("</script>");


                this.Page.ClientScript.RegisterStartupScript(Type.GetType("Hutchinson.WebControls.HutchRadioButtonList"), "Hutchinson.WebControls.RadioButtonList", sb.ToString());
            }

            base.OnInit(e);
        }

        protected override void CreateChildControls()
        {

            if (!bRequired)
            {
                string idPreSelected = string.Empty;
                foreach (ListItem Item in this.Items)
                {
                    Item.Attributes.Add("onclick", string.Format("uncheckChecked(this,'{0}');", this.ClientID));
                    if (Item.Selected)
                        idPreSelected = string.Format("{0}_{1}", this.ClientID, this.Items.IndexOf(Item));
                }
                this.Attributes.Add("PrevSelectedID", idPreSelected);
            }

            base.CreateChildControls();
        }

    }

}